#include <iostream>
#include <cstring>  // For memset
#include <snappy.h>
#include <chrono>
#include "test.pb.h"  // Protobuf 生成的头文件

// 定义缓冲区大小
const size_t BUFFER_SIZE = 4096;

int main() {
    // 创建 Protobuf 消息
    TestEncrypt message;
    message.set_content("压缩和解压缩成功 压缩和解压缩成功 压缩和解压缩成功 压缩和解压缩成功 压缩和解压缩成功 压缩和解压缩成功");

    // 序列化 Protobuf 消息
    uint8_t serialized_message[BUFFER_SIZE];
    int message_size = message.ByteSizeLong();
    if (message_size > BUFFER_SIZE) {
        std::cerr << "Message size exceeds buffer size" << std::endl;
        return -1;
    }

    if (!message.SerializeToArray(serialized_message, BUFFER_SIZE)) {
        std::cerr << "Failed to serialize Protobuf message" << std::endl;
        return -1;
    }

    std::cout << "原始消息大小: " << message_size << " bytes" << std::endl;

    // 压缩消息
    std::string compress_str;
    if (!snappy::Compress(reinterpret_cast<const char*>(serialized_message), message_size, &compress_str)) {
        std::cerr << "Failed to compress data" << std::endl;
        return -1;
    }
    std::cout << "压缩后大小: " << compress_str.size() << " bytes" << std::endl;

    // 计算1000万此压缩耗时
    auto start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < 10000000; ++i) {
        if (!snappy::Compress(reinterpret_cast<const char*>(serialized_message), message_size, &compress_str)) {
            std::cerr << "Failed to compress data" << std::endl;
            return -1;
        }
    }
    auto end = std::chrono::high_resolution_clock::now();
    std::cout << "1000万次压缩耗时: " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl;


    // 计算1000万此解压耗时
    std::string uncompress_str;
    start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < 10000000; ++i) {
        uint8_t decompressed[BUFFER_SIZE];
        size_t decompressed_size = BUFFER_SIZE;
        if (!snappy::Uncompress(compress_str.c_str(), compress_str.size(), &uncompress_str))
        {
            std::cerr << "Failed to decompress data" << std::endl;
            return -2;
        }
    }
    end = std::chrono::high_resolution_clock::now();
    std::cout << "1000万次解压耗时: " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl;


    // 反序列化 Protobuf 消息
    TestEncrypt decompressedMessage;
    if (!decompressedMessage.ParseFromString(uncompress_str)) {
        std::cerr << "Failed to parse Protobuf message" << std::endl;
        return -1;
    }

    // 打印解压缩后的内容
    std::cout << "解压缩后消息内容: " << decompressedMessage.content() << std::endl;

    return 0;
}
